package fr.kptn.musixmatchwrapper.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import fr.kptn.musixmatchwrapper.exception.MusixmatchWrapperException;

/**
 * Utility class to build URL requests
 * 
 * @author Sylvain
 * 
 */
public class URLHelper {

	/**
	 * This method build requests based on the method name and the parameters to
	 * this method
	 * 
	 * @param pMethodName
	 *            the name of the method to request musiXmatch API
	 * @param pParameters
	 *            the parameters to use in this request to the musiXmatch API
	 * @return the constructed request
	 * @throws MusixmatchWrapperException
	 */
	public static String buildRequest(String pMethodName, Map<String, Object> pParameters) throws MusixmatchWrapperException {
		StringBuffer lRequestSB = new StringBuffer();

		lRequestSB.append(pMethodName).append(Constants.URL_BEGIN_PARAM_DELIMITER);
		try {
			for (Entry<String, Object> lEntry : pParameters.entrySet()) {
				lRequestSB.append(lEntry.getKey()).append(Constants.URL_VALUE_DELIMITER)
						.append(URLEncoder.encode(lEntry.getValue().toString(), Constants.API_ENCODING));

				lRequestSB.append(Constants.URL_PARAM_DELIMITER);
			}
		} catch (UnsupportedEncodingException e) {
			throw new MusixmatchWrapperException("An error occured during the encoding of URL parameters");
		}

		return lRequestSB.toString().substring(0, lRequestSB.length() - 1);
	}
}
